# -*-coding:utf-8-*-
import argparse
import commands
import json
import urllib2
import time
import sys
parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument('--type', type=str, default = None)
parser.add_argument('--etidion', type=int, default=32)
parser.add_argument('--restart', type=str, default = None)
parser.add_argument('--project', type=str, default=None)
args = parser.parse_args()

USERNAME="svnco"
PASSWD="123456"

if args.type == "tomcat":
  path="/data/app/"+args.project+"/webapps/ROOT"
elif args.type == "java":
  path="/data/app/"+args.project
else:
  sys.exit(0)
status , info = commands.getstatusoutput('/usr/bin/svn up -r %s --username %s --password %s %s'%(args.etidion,USERNAME,PASSWD,path)) #更新操作
if status == 0:
  status , info = commands.getstatusoutput('/usr/bin/chown %s:%s %s -R'%(args.project,args.project,path)) #更改文件权限
  if status == 0: 
    if args.restart == "y":
      status , info = commands.getstatusoutput('/usr/sbin/service  %s restart'%(args.project))
      if status == 0:
        time.sleep(10)
        frequency=0
        CheckID="service:"+str(args.project)
        while True:
          url = "http://127.0.0.1:8500/v1/agent/checks"
          req = urllib2.Request(url)
          resp = urllib2.urlopen(req)
          service_info = json.loads(resp.read())
          if service_info[CheckID]['Status'] == "passing":
            print "complete"
            break
          time.sleep(5)
          frequency+=1
          if frequency > 10 :
            print "consul error"
            break
      else:
        print "restart error"
    else:
      print "complete"
  else:
    print "chown error"
else:
  print "svn up error"
